<template>
  <view class="notice-container">
    <!-- 搜索区域 -->
    <view class="search-area">
      <!-- 搜索和状态筛选在同一行 -->
      <view class="search-row">
        <!-- 状态筛选 -->
        <view class="status-picker">
          <picker mode="selector" :range="statusOptions" range-key="dictLabel" @change="handleStatusChange" class="picker">
            <view class="picker-text">{{currentStatus.dictLabel}}</view>
          </picker>
        </view>
        
        <!-- 标题搜索 -->
        <view class="search-box">
          <text class="iconfont icon-search search-icon"></text>
          <input 
            type="text" 
            class="search-input" 
            placeholder="请输入公告标题"  
            confirm-type="search"
            v-model="searchTitle"
            @confirm="handleSearch"
          />
          <text class="iconfont icon-close clear-icon" v-if="searchTitle" @tap="clearSearch"></text>
        </view>
        <view class="search-btn" @tap="handleSearch">搜索</view>
      </view>
    </view>
    
    <!-- 公告列表 -->
    <scroll-view 
      scroll-y 
      class="notice-list" 
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="notice-card" v-for="(item, index) in noticeList" :key="index" @tap="viewNoticeDetail(item)">
        <view class="notice-title">{{item.title}}</view>
        <view class="notice-info">
          <view class="notice-tags-row">
            <view class="notice-tags">
              <text class="notice-tag">{{item.companyTypeText || getCompanyTypeText(item.companyType) || '暂无'}}</text>
              <text class="notice-tag">{{item.isWeaveText || (item.isWeave !== undefined ? (item.isWeave ? '带编' : '不带编') : '暂无')}}</text>
            </view>
            <text class="notice-status" :class="[getStatusClass(item.status)]">{{getStatusText(item.applyStatus)}}</text>
          </view>
          <view class="notice-detail">
            <text class="notice-detail-item">招聘人数：{{item.recruitNum || '暂无'}}</text>
            <text class="notice-detail-item">地址：{{item.address || '暂无'}}</text>
            <text class="notice-detail-item">报名时间：{{ (item.startTime && item.endTime) ? `${formatDate(item.startTime)} ~ ${formatDate(item.endTime)}` : '暂无' }}</text>
          </view>
        </view>
      </view>
      
      <!-- 加载更多提示 -->
      <view class="loading-more" v-if="noticeList.length > 0">
        <text v-if="isLoading">加载中...</text>
        <text v-else-if="!hasMore">没有更多数据了</text>
      </view>
      
      <!-- 空状态提示 -->
      <view class="empty-state" v-if="noticeList.length === 0 && !isLoading">
        <text class="empty-text">暂无关注公告</text>
        <view class="reset-filter-btn" @tap="resetAllFilters">重置筛选条件</view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getLikeNoticeList } from '@/api/notice/recruitNotice';
import { getDicts } from '@/api/dict/data.js'
export default {
  computed: {
    // 公司类型选项
    companyTypeOptions() {
      return [{ dictValue: '', dictLabel: '全部' }].concat(this.companyTypeDict);
    },
    // 是否带编选项
    yesOrNoOptions() {
      return [{ dictValue: '', dictLabel: '全部' }].concat(this.yesOrNoDict);
    },
    // 报名状态选项
    statusOptions() {
      return [{ dictValue: '', dictLabel: '全部' }].concat(this.applyStatusDict);
    }
  },
  data() {
    return {
      statusBarHeight: 0,
      noticeList: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      isLoading: false,
      isRefreshing: false,
      hasMore: true,
      searchTitle: '', // 搜索标题关键词
      originalNoticeList: [], // 保存原始数据用于搜索
      // 当前选中的状态
      currentStatus: { dictValue: '', dictLabel: '全部' },
      // 字典类型名称
      companyTypeDictType: 'recruit_company_type', // 公司类型字典
      applyStatusDictType: 'recruit_notice_status', // 报名状态字典
      yesOrNoDictType: 'recruit_yes_no', // 是否字典
      
      // 字典数据
      companyTypeDict: [], // 公司类型字典
      applyStatusDict: [], // 报名状态字典
      yesOrNoDict: [] // 是否字典
    }
  },
  onLoad() {
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight;
    
    // 加载字典数据
    this.loadDictData();
    
    // 加载公告数据
    this.fetchNoticeList();
  },
  methods: {
    // 处理状态变化
    handleStatusChange(e) {
      const index = e.detail.value;
      this.currentStatus = this.statusOptions[index];
      this.filterNoticeList();
    },
    // 获取公告列表
    async fetchNoticeList(isRefresh = false) {
      if (this.isLoading) return;
      
      this.isLoading = true;
      
      if (isRefresh) {
        this.pageNum = 1;
        this.noticeList = [];
        this.hasMore = true;
      }
      
      try {
        // 构建查询参数
        const queryParams = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          title: this.searchTitle || undefined,
          status: this.currentStatus.dictValue || undefined
        };
        
        // 调用API获取关注公告列表
        const response = await getLikeNoticeList(queryParams);
        
        if (response && response.code === 200) {
          const rows = response.rows;
          const total = response.total;
          
          // 处理数据
          const processedRows = this.processNoticeData(rows);
          
          if (isRefresh) {
            this.noticeList = processedRows || [];
            this.originalNoticeList = [...this.noticeList];
          } else {
            this.noticeList = [...this.noticeList, ...(processedRows || [])];
            this.originalNoticeList = [...this.originalNoticeList, ...(processedRows || [])];
          }
          
          this.total = total || 0;
          this.hasMore = this.noticeList.length < this.total;
        } else {
          uni.showToast({
            title: response?.msg || '获取公告列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载数据失败', error);
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
        this.isRefreshing = false;
      }
    },
    
    // 处理搜索
    handleSearch() {
      // 重置页码并重新获取数据
      this.pageNum = 1;
      this.fetchNoticeList(true);
    },
    
    // 过滤公告列表 - 通过API重新获取数据
    filterNoticeList() {
      // 重置页码并重新获取数据
      this.pageNum = 1;
      this.fetchNoticeList(true);
    },
    
    // 清除搜索内容
    clearSearch() {
      this.searchTitle = '';
      // 重新获取数据
      this.filterNoticeList();
    },
    
    // 下拉刷新
    onRefresh() {
      this.isRefreshing = true;
      this.fetchNoticeList(true);
    },
    
    // 加载更多
    loadMore() {
      if (!this.hasMore || this.isLoading) return;
      
      this.pageNum++;
      this.fetchNoticeList();
    },
    
    // 查看公告详情
    viewNoticeDetail(item) {
      uni.navigateTo({
        url: `/pagesA/recruitNotice/detail?noticeId=${item.noticeId}`
      });
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '--';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    
    // 获取状态文本
    getStatusText(value) {
      if (!value && value !== 0) return '--';
      const dictValue = String(value);
      const dictItem = this.applyStatusDict.find(item => item.dictValue === dictValue);
      return dictItem ? dictItem.dictLabel : '--';
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      const classMap = {

        3: 'status-coming',    // 即将报名
        1: 'status-ongoing',     // 正在报名
        2: 'status-closing',      // 即将截止
        4: 'status-closed'        // 结束报名
      };
      return classMap[status] || '';
    },
    
    // 获取公司类型文本
    getCompanyTypeText(value) {
      if (!value && value !== 0) return '--';
      const dictValue = String(value);
      const dictItem = this.companyTypeDict.find(item => item.dictValue === dictValue);
      return dictItem ? dictItem.dictLabel : '--';
    },
    
    // 获取是否带编文本
    getYesNoText(value) {
      if (value === undefined || value === null) return '--';
      const dictValue = String(value);
      const dictItem = this.yesOrNoDict.find(item => item.dictValue === dictValue);
      return dictItem ? dictItem.dictLabel : '--';
    },
    
    // 处理公告数据转换
    processNoticeData(rows) {
      if (!rows || !Array.isArray(rows)) return [];
      
      return rows.map(item => {
        // 可以在这里进行数据转换和处理
        return {
          ...item,
          // 如果需要添加额外的处理字段，可以在这里添加
          formattedStartTime: this.formatDate(item.startTime),
          formattedEndTime: this.formatDate(item.endTime),
          formattedRecruitTime: (item.startTime && item.endTime) ? 
            `${this.formatDate(item.startTime)} ~ ${this.formatDate(item.endTime)}` : '暂无',
          statusText: this.getStatusText(item.status),
          companyTypeText: this.getCompanyTypeText(item.companyType),
          isWeaveText: item.isWeave !== undefined ? (item.isWeave ? '带编' : '不带编') : '暂无',
          recruitNum: item.recruitNum || '暂无',
          address: item.address || '暂无'
        };
      });
    },
    
    // 重置所有筛选条件
    resetAllFilters() {
      // 显示加载提示
      uni.showLoading({
        title: '重置中...'
      });
      
      // 重置搜索关键词
      this.searchTitle = '';
      
      // 重置状态筛选
      this.currentStatus = { dictValue: '', dictLabel: '全部' };
      
      // 重置页码
      this.pageNum = 1;
      
      // 重新获取数据
      this.fetchNoticeList(true).finally(() => {
        uni.hideLoading();
        uni.showToast({
          title: '已重置筛选条件',
          icon: 'success',
          duration: 1500
        });
      });
    },
    
    // 加载字典数据
    async loadDictData() {
      try {
        // 并行加载所有字典数据
        const [companyTypeRes, applyStatusRes, yesOrNoRes] = await Promise.all([
          getDicts(this.companyTypeDictType),
          getDicts(this.applyStatusDictType),
          getDicts(this.yesOrNoDictType)
        ]);
        
        // 处理公司类型字典
        if (companyTypeRes && companyTypeRes.code === 200) {
          this.companyTypeDict = companyTypeRes.data || [];
        }
        
        // 处理报名状态字典
        if (applyStatusRes && applyStatusRes.code === 200) {
          this.applyStatusDict = applyStatusRes.data || [];
        }
        
        // 处理是否字典
        if (yesOrNoRes && yesOrNoRes.code === 200) {
          this.yesOrNoDict = yesOrNoRes.data || [];
        }
      } catch (error) {
        console.error('加载字典数据失败', error);
        uni.showToast({
          title: '加载字典数据失败',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style>
.notice-container {
  min-height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* 固定区域样式 */
.fixed-section {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
  background: #f5f7fa;
  padding: 10rpx 24rpx;
  padding-top: calc(var(--status-bar-height) - 10rpx);
}

/* 标题区域样式 */
.header-section {
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  padding: 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 搜索区域样式 */
.search-area {
  position: fixed;
  top: var(--status-bar-height-10px);
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 24rpx;
  z-index: 100;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  width: 100%;
  min-height: 110rpx;
  display: flex;
  flex-direction: column;
}

/* 搜索行样式 */
.search-row {
  display: flex;
  align-items: center;
}

.status-picker {
  width: 240rpx;
  height: 70rpx;
  background-color: #f5f7fa;
  border-radius: 8rpx;
  margin-right: 20rpx;
  padding: 0 10rpx;
  box-sizing: border-box;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  height: 70rpx;
  border-radius: 8rpx;
  padding: 0 20rpx;
  margin-right: 20rpx;
  box-sizing: border-box;
}

.search-icon {
  font-size: 28rpx;
  color: #999;
  margin-right: 10rpx;
}

.search-input {
  flex: 1;
  height: 100%;
  font-size: 28rpx;
  color: #333;
}

.clear-icon {
  font-size: 24rpx;
  color: #999;
  padding: 10rpx;
}

.search-btn {
  width: 120rpx;
  height: 70rpx;
  background-color: #409EFF;
  color: #fff;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
}

/* 公告列表样式 */
.notice-list {
  flex: 1;
  margin-top: calc(var(--status-bar-height) + 80rpx);
  height: calc(100vh - var(--status-bar-height) - 80rpx);
  padding: 10rpx 24rpx;
  box-sizing: border-box;
}

/* 筛选区域样式 */
.filter-section {
  margin-bottom: 15rpx;
}

.filter-box {
  background-color: #f5f7fa;
  border-radius: 8rpx;
  padding: 0 10rpx;
}

.filter-row {
  display: flex;
  align-items: center;
}

.filter-item {
  flex: 1;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.filter-half {
  width: 50%;
}

.picker {
  width: 100%;
  height: 70rpx;
}

.picker-text {
  height: 70rpx;
  line-height: 70rpx;
  font-size: 28rpx;
  color: #333;
  text-align: center;
}

.notice-card {
  padding: 20rpx 16rpx;
  border-bottom: 1rpx solid #eee;
  position: relative;
  width: 100%;
  box-sizing: border-box;
  overflow: visible;
  background: #fff;
}

.notice-card:last-child {
  border-bottom: none;
}

.notice-card:active {
  background-color: #f9f9f9;
}

.notice-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 14rpx;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  padding-right: 4rpx;
  word-break: break-all;
}

.notice-info {
  margin-top: 16rpx;
}

.notice-tags-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.notice-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8rpx;
}

.notice-tag {
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 4rpx;
  background: #f5f5f5;
  color: #666;
  margin-bottom: 4rpx;
  white-space: nowrap;
  max-width: 100%;
}

.notice-detail {
  display: flex;
  flex-direction: column;
  margin-bottom: 10rpx;
}

.notice-detail-item {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 4rpx;
}

.notice-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 6rpx;
  flex-wrap: wrap;
}

.notice-time {
  font-size: 22rpx;
  color: #888;
  background-color: #f8f8f8;
  padding: 4rpx 10rpx;
  border-radius: 4rpx;
  margin-right: 8rpx;
}

.notice-status {
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  font-weight: normal;
}

/* 状态样式 */
.status-coming {
  color: #409EFF;
  background-color: rgba(64, 158, 255, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  font-weight: normal;
}

.status-ongoing {
  color: #67C23A;
  background-color: rgba(103, 194, 58, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  font-weight: normal;
}

.status-closing {
  color: #E6A23C;
  background-color: rgba(230, 162, 60, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  font-weight: normal;
}

.status-closed {
  color: #F56C6C;
  background-color: rgba(245, 108, 108, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  font-weight: normal;
}

/* 加载更多提示 */
.loading-more {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
}

/* 空状态提示 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 30rpx;
}

.reset-filter-btn {
  margin-top: 20rpx;
  padding: 16rpx 40rpx;
  background-color: #409EFF;
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  display: inline-block;
}
</style> 